package com.sniper.serviceribbon.controller;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.sniper.model.LineShop;
import com.sniper.serviceribbon.hystrix.LineShopCollapseCommand;
import com.sniper.serviceribbon.service.HelloService;
import com.sniper.serviceribbon.service.LineShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author suzhen
 * @create 2018/3/6
 */
@RestController
public class HelloController {

    @Autowired
    HelloService helloService;

    @Autowired
    LineShopService lineShopService;

    @ResponseBody
    @RequestMapping(value = "/hi")
    public String hi(@RequestParam String name) {
        return helloService.hiService(name);
    }

    @ResponseBody
    @RequestMapping(value = "/line-shop/get/{id}")
    public LineShop get(@PathVariable String id) {
        return lineShopService.get(id);
    }

    /**
     * 请求合并例子
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/line-shop/getc/{id}")
    public LineShop getCommand(@PathVariable String id) {
        HystrixRequestContext context = HystrixRequestContext.initializeContext();
        LineShopCollapseCommand collapseCommand = new LineShopCollapseCommand(lineShopService, id);
        Future<LineShop> lineShopFuture = collapseCommand.queue();
        LineShop lineShop = null;
        try {
            lineShop = lineShopFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        context.close();
        return lineShop;
    }

    @ResponseBody
    @RequestMapping(value = "/line-shop/list/{id}")
    public List list(@PathVariable String id) {
        return lineShopService.list(id);
    }
}
